package com.luck.easyfoodbatch.ui;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.custom.RichTextEditor;
import com.luck.easyfoodbatch.entity.Product;
import com.luck.easyfoodbatch.mvp.mine.EditGoods2Model;
import com.luck.easyfoodbatch.mvp.mine.EditGoods2Presenter;
import com.luck.easyfoodbatch.mvp.mine.EditGoods2View;
import com.luck.easyfoodbatch.mvp.mine.GoodsDetailModel;
import com.luck.easyfoodbatch.mvp.mine.GoodsDetailPresenter;
import com.luck.easyfoodbatch.mvp.mine.GoodsDetailView;
import com.luck.easyfoodbatch.mvp.mine.UploadImageModel;
import com.luck.easyfoodbatch.mvp.mine.UploadImageView;
import com.luck.easyfoodbatch.mvp.mine.UploadSinglePresenter;
import com.luck.easyfoodbatch.mvp.model.EditGoods;
import com.luck.easyfoodbatch.mvp.model.GoodsDetail;
import com.luck.easyfoodbatch.mvp.model.UploadModel;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;
import com.luck.picture.lib.model.FunctionConfig;
import com.luck.picture.lib.model.PictureConfig;
import com.yalantis.ucrop.entity.LocalMedia;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class UploadGraphicDetailsActivity extends BaseActivity implements UploadImageView, GoodsDetailView, EditGoods2View {
    private final String TAG = "UploadGraphicDetailsActivity";
    @BindView(R.id.richEditor)
    RichTextEditor richEditor;
    private List<LocalMedia> photoInfos = new ArrayList<>();
    @BindView(R.id.btn_next_graphic)
    Button btnNextGraphic;
    @BindView(R.id.tv_addImg)
    TextView tvAddImg;
    private UploadImageModel imageModel;
    private String richText = "", title = "";
    private Product product;
    private int type = 0;
    private GoodsDetailModel detailModel;
    private final static String regxpForImageTagSrcAttrib = "<p>([^</p>]*)|src=\"([^\"]+)\""; // 匹配<p>标签或<img>
    private EditGoods2Model goods2Model;
    private String gid = "";
    private int product_type = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type = getIntent().getIntExtra("type", 0);
        if (type == 1) {
            title = "修改商品(商品详情)";

        } else {
            title = "上传商品(商品详情)";
        }
        setContentView(R.layout.activity_upload_graphic_details, title, MODE_BACK_NAVIGATION);
        ButterKnife.bind(this);
        product_type = getIntent().getIntExtra("product_type", 0);
        product = (Product) getIntent().getSerializableExtra("product");
        if (type == 1) {
            // 编辑状态
            btnNextGraphic.setText("保存");
            gid = getIntent().getStringExtra("gid");
            detailModel = new GoodsDetailPresenter(this, mContext);
            showProgressDialog(getString(R.string.app_loading));
            detailModel.requestGoodsDetail(gid);
        }
    }

    @OnClick({R.id.btn_next_graphic, R.id.tv_addImg})
    public void onClick(View v) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        switch (v.getId()) {
            case R.id.tv_addImg:
                FunctionConfig options = new FunctionConfig();
                options.setCompress(true);
                options.setSelectMode(FunctionConfig.MODE_SINGLE);
                PictureConfig.init(options);
                PictureConfig.getPictureConfig().openPhoto(UploadGraphicDetailsActivity.this, resultCallback);
                break;
            case R.id.btn_next_graphic:
                richText = richEditor.getRichEditDataString();
                if (Tools.isNull(richText)) {
                    T.showToast(mContext, "请输入商品详情");
                } else {
                    if (product == null) {
                        product = new Product();
                        product.setGid(gid);
                    }
                    product.setContent(richText);
                    if (type == 1) {
                        // 编辑状态
                        showProgressDialog(getString(R.string.app_loading));
                        goods2Model = new EditGoods2Presenter(this, mContext);
                        goods2Model.requestEditGoods(1, product);

                    } else {
                        intent.setClass(mContext, UploadCertificateActivity.class);
                        bundle.putSerializable("product", product);
                        bundle.putInt("product_type", product_type);
                        intent.putExtras(bundle);
                        startActivityForResult(intent, 200);
                    }
                }
                break;
        }
    }


    @Override
    public void uploadSuccess(UploadModel model) {
        if (model.getStatus() == HttpUtil.RESULT_OK) {
            List<String> data = model.getData();

            if (data != null && data.size() > 0) {
                String avatar = data.get(0);
                Log.v("gg",HttpUtil.IMG_BASE_URL + avatar);
                richEditor.insertImageByURL(HttpUtil.IMG_BASE_URL + avatar);
            }
        } else {
            T.showToast(mContext, model.getMsg());
        }
    }

    @Override
    public void getGoodsDetailSuccess(GoodsDetail model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                GoodsDetail.DataBean modelData = model.getData();
                if (modelData != null) {
                    String content = modelData.getContent();
                    Pattern p = Pattern.compile(regxpForImageTagSrcAttrib);// 匹配<title>开头，</title>结尾的文档
                    Matcher m = p.matcher(content);// 开始编译
                    while (m.find()) {
                        String group1 = m.group(1);
                        String group2 = m.group(2);
                        if (group1 != null) {
                            // 文字
                            richEditor.insertText(group1);
                        }
                        if (group2 != null) {
                            // 图片
                            richEditor.insertImageByURL(group2);
                        }
                    }
                }
            }
        }

    }

    @Override
    public void editGoods2Success(EditGoods model) {
        if (model != null && model.getStatus() == HttpUtil.RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        }
    }

    @Override
    public void httpStatusError() {

    }

    @Override
    public void hideLoading() {
        hideShowProgress();
    }

    @Override
    public void upProgress(long currentSize, long totalSize, float progress, long networkSpeed) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 200:
                    setResult(RESULT_OK);
                    finish();
                    break;
            }
        }
    }

    private PictureConfig.OnSelectResultCallback resultCallback = new PictureConfig.OnSelectResultCallback() {
        @Override
        public void onSelectSuccess(List<LocalMedia> list) {
            photoInfos = list;
            if (photoInfos != null || photoInfos.size() > 0) {
                LocalMedia media = photoInfos.get(0);
                File file;
                if (media.isCompressed()) {
                    file = new File(media.getCompressPath());
                } else {
                    file = new File(media.getPath());
                }
                showProgressDialog("正在处理，请稍候……");
                imageModel = new UploadSinglePresenter(UploadGraphicDetailsActivity.this, mContext);
                imageModel.uploads(0, file, null);
            }
        }
    };
}
